#!/usr/bin/python
from xmpp import XMPP_handler
from email.header import decode_header
from email.utils import getaddresses
from google.appengine.api import mail
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class Mail_handler(webapp.RequestHandler):
  def post(self, recepient):
    try:
      func = getattr(self, 'func_' + recepient)
    except AttributeError:
      pass
    else:
      try:
        self._message = mail.InboundEmailMessage(self.request.body)
      except mail.Error:
        pass
      else:
        sender = getaddresses([self._message.sender])
        if sender:
          self._sender = sender[0][1]
          func()

  def func_status(self):
    xmpph = XMPP_handler()
    subject = ''
    s = decode_header(self._message.subject)
    for v in s:
      subject += v[0].decode(v[1]) if v[1] else v[0]
    xmpph.process(xmpp.Message({'from': self._sender, 'to': self._message.to, 'body': subject}))


if __name__ == "__main__":
  application = webapp.WSGIApplication([('/_ah/mail/(.*)%40.*', Mail_handler)])
  run_wsgi_app(application)
